<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * Version :  v1.0.0
 * Date    :  2023/5/31 17:05
 */

namespace App\Exception\Handler;

use Hyperf\Codec\Json;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use App\Exception\ServiceException;
use Throwable;
class ServiceExceptionHandler extends  ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 判断被捕获到的异常是希望被捕获的异常
        if ($throwable instanceof ServiceException) {
            if (! $response->hasHeader('content-type')) {
                $response = $response->withAddedHeader('content-type', 'text/plain; charset=utf-8');
            }
            // 组装消息体
            $msgData = json_decode($throwable->getMessage(),true);
            // 阻止异常冒泡
            $this->stopPropagation();
            return $response->withStatus((int)$throwable->getCode())->withBody(new SwooleStream(Json::encode($msgData)));
        }

        // 交给下一个异常处理器
        return $response;

        // 或者不做处理直接屏蔽异常
    }

    /**
     * 判断该异常处理器是否要对该异常进行处理
     */
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}